//
//  XNUtil.m
//  XINNingOA
//
//  Created by samuel on 2021/7/16.
//

#import "XNUtil.h"
#import "XNCommonBillViewController.h"
#import "XNAdministrativeViewController.h"
#import "XNExpenseViewController.h"
#import "XNCommunicationViewController.h"
#import "XNTravelViewController.h"
#import "XNEducationViewController.h"
#import "XNCareConfirmViewController.h"
#import "XNLoadBudgetViewController.h"
#import "XNUserResignViewController.h"
#import "XNPurchaseViewController.h"
#import "XNUseCarViewController.h"
#import "XNPayInfoViewController.h"
#import "XNFixedAssetViewController.h"
#import "XNAllotViewController.h"
#import "XNScrapViewController.h"
#import "XNPublicResourceViewController.h"
#import "XNSupplierViewController.h"
#import "XNContractViewController.h"
#import "XNSealViewController.h"
#import "XNApprovalViewController.h"
#import "XNFixPurchaseViewController.h"
#import "XNFixPayViewController.h"

@implementation XNUtil

+(XNBaseBillInfoViewController *)getControllerWithOrderId:(NSString *)orderId
{
    XNBaseBillInfoViewController *vc;
    NSString *billCode = [orderId substringToIndex:2];
    if ([billCode isEqualToString:@"TB"]) {//通用报销单
        vc = [[XNCommonBillViewController alloc] init];

    }else if([billCode isEqualToString:@"XB"]){//行政事务报销单
        vc = [[XNAdministrativeViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"FY"]){//费用类申请单
        vc = [[XNExpenseViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"JF"]){//交际费用申请/报销单
        vc = [[XNCommunicationViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"TR"]){//差旅报销单
        vc = [[XNTravelViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"PX"]){//培训类申请单
        vc = [[XNEducationViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"WR"]){//服务/维修/保养确认单
        vc = [[XNCareConfirmViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"BB"] || [billCode isEqualToString:@"BC"]){//部门/公司年度预算单
        vc = [[XNLoadBudgetViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"LZ"]){//离职申请单
        vc = [[XNUserResignViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"PO"]){//采购申请单
        vc = [[XNPurchaseViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"YC"]){//车辆使用申请单
        vc = [[XNUseCarViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"PY"]){//运输结算申请单
        vc = [[XNPayInfoViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"DJ"]){//固定资产登记单
        vc = [[XNFixedAssetViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"DB"]){//固定资产调拨单
        vc = [[XNAllotViewController alloc] init];
        vc.orderId = orderId;
    }else if([billCode isEqualToString:@"BF"]){//国定资产报废单
        vc = [[XNScrapViewController alloc] init];
    }else if([billCode isEqualToString:@"PR"]){//公共资产申请单
        vc = [[XNPublicResourceViewController alloc] init];
    }else if([billCode isEqualToString:@"SP"]){//供应商资质审核单
        vc = [[XNSupplierViewController alloc] init];
    }else if([billCode isEqualToString:@"CP"]){//合同审核单据
        vc = [[XNContractViewController alloc] init];
    }else if([billCode isEqualToString:@"SA"]){//用印申请单
        vc = [[XNSealViewController alloc] init];
    }else if([billCode isEqualToString:@"AP"]){//送审签申请单
        vc = [[XNApprovalViewController alloc] init];
    }else if([billCode isEqualToString:@"FA"]){//固资采购单
        vc = [[XNFixPurchaseViewController alloc] init];
    }else if([billCode isEqualToString:@"FB"]){//固资报销单
        vc = [[XNFixPayViewController alloc] init];
    }else{
        vc = [[XNBaseBillInfoViewController alloc] init];
    }
    vc.orderId = orderId;
    return vc;
}

+ (UIViewController *)parentControllerFromView:(UIView *)view
{
    for (UIView* next = [view superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

+ (void)checkVersion{
    
    //获取APP自身版本号
//    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    
    //定义的App地址
    NSString *appID = @"1577287147";
    NSString *urlStr = [NSString stringWithFormat:@"http://itunes.apple.com/cn/lookup?id=%@",appID];
    
    
    //网络请求App的信息（我们取Version就够了）
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                       timeoutInterval:10];
    
    [request setHTTPMethod:@"POST"];
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSMutableDictionary *receiveStatusDic=[[NSMutableDictionary alloc]init];
        if (data) {
            
            //data是有关于App所有的信息
            NSDictionary *receiveDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if ([[receiveDic valueForKey:@"resultCount"] intValue]>0) {
                
                [receiveStatusDic setValue:@"1" forKey:@"status"];
                [receiveStatusDic setValue:[[[receiveDic valueForKey:@"results"] objectAtIndex:0] valueForKey:@"version"]   forKey:@"version"];
                
                //请求的有数据，进行版本比较
                [self receiveData:receiveStatusDic];
//                [self performSelectorOnMainThread:@selector(receiveData:) withObject:receiveStatusDic waitUntilDone:NO];
            }else{
                
                [receiveStatusDic setValue:@"-1" forKey:@"status"];
            }
        }else{
            [receiveStatusDic setValue:@"-1" forKey:@"status"];
        }
        
    }];
    
    [task resume];
    
    
    
}


+(void)receiveData:(id)sender
{
    //获取APP自身版本号
    NSString *localVersion = [[[NSBundle mainBundle]infoDictionary]objectForKey:@"CFBundleShortVersionString"];
    
    NSArray *localArray = [localVersion componentsSeparatedByString:@"."];
    NSArray *versionArray = [sender[@"version"] componentsSeparatedByString:@"."];
    
    
    if ((versionArray.count == 3) && (localArray.count == versionArray.count)) {
        
        if ([localArray[0] intValue] <  [versionArray[0] intValue]) {
            [self updateVersion];
        }else if ([localArray[0] intValue]  ==  [versionArray[0] intValue]){
            if ([localArray[1] intValue] <  [versionArray[1] intValue]) {
                [self updateVersion];
            }else if ([localArray[1] intValue] ==  [versionArray[1] intValue]){
                if ([localArray[2] intValue] <  [versionArray[2] intValue]) {
                    [self updateVersion];
                }
            }
        }
    }
    
}


+(void)updateVersion{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *msg = [NSString stringWithFormat:@"又出新版本啦，快点更新吧!"];
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"升级提示" message:msg preferredStyle:UIAlertControllerStyleAlert];
        
        // Create the actions.
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"现在升级"style:UIAlertActionStyleDestructive handler:^(UIAlertAction*action) {
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/app/id1577287147?mt=8"]];
            [[UIApplication sharedApplication] openURL:url];
            
            
        }];
        
        // Add the actions.
        [alertController addAction:cancelAction];
        [alertController addAction:otherAction];
        
        [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
    });

    
}

@end
